package com.me.study.rabbitmq.rabbit;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.ErrorMessage;
import org.springframework.stereotype.Component;

/**
 * 发生异常时的消息返回提醒
 * 需要开启
 * # 开启发送失败退回
 * publisher-returns: true
 * @author hw
 * @date 2019-07-22 15:45
 **/
@Slf4j
@Component
public class MessageReturn implements RabbitTemplate.ReturnsCallback {


    @Override
    public void returnedMessage(ReturnedMessage returned) {
        log.info("返回消息回调:{} 应答代码:{} 回复文本:{} 交换器:{} 路由键:{}", returned.getMessage(), returned.getReplyCode(),
                returned.getReplyText(), returned.getExchange(), returned.getRoutingKey());
    }

    @ServiceActivator(inputChannel = "TestDirectExchange.cloudstream.errors")
    public void handleError(ErrorMessage message) {
        Throwable throwable = message.getPayload();
        System.out.println("截获异常 "+ throwable);

        Message<?> originalMessage = message.getOriginalMessage();
        assert originalMessage != null;

        System.out.println("原始消息体 = {}"+new String((byte[]) originalMessage.getPayload()));
    }

}